package com.vectquant.lwwl_service01.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.Buffer;
import java.text.CompactNumberFormat;
import java.util.Map;

/**
 * HTTP请求工具类
 */
public class HttpUtil {
    /**
     * 发送post请求
     * @param urlStr请求URL
     * @param jsonBody 请求体json字符串
     * @param headers 请求头
     * @return 相应内容
     */
    public static String post(String urlStr, String jsonBody, Map<String,String> headers){
        HttpURLConnection connection = null;
        try{
            // 验证参数
            if (urlStr == null || urlStr.isEmpty()) {
                throw new IllegalArgumentException("URL不能为空");
            }
//            创建URL对象
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
//            设置请求方法
            connection.setRequestMethod("POST");

            connection.setDoOutput(true);
            // 设置连接和读取超时（防止请求挂起）
            connection.setConnectTimeout(30000); // 15秒连接超时
            connection.setReadTimeout(60000);    // 15秒读取超时

//            设置请求头
            if (headers!=null){
                for (Map.Entry<String ,String> entry : headers.entrySet()){
                    connection.setRequestProperty(entry.getKey(),entry.getValue());
                    connection.setRequestProperty("Connection", "Keep-Alive");
                }
            }

//            写入请求体
            if (jsonBody != null && !jsonBody.isEmpty()){
                try(OutputStream os = connection.getOutputStream()){
                    byte[] input = jsonBody.getBytes("utf-8");
                    os.write(input,0,input.length);
                }
            }



//            获取响应
            int status = connection.getResponseCode();

            // 读取响应 - 使用安全的方式获取输入流
            InputStream inputStream;
            if (status >= 200 && status < 300) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
            }

            // 检查输入流是否为空
            if (inputStream == null) {
                throw new RuntimeException("HTTP响应流为空，状态码: " + status);
            }
            // 读取响应内容
            try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }

                String responseText = response.toString();

                if (status >= 200 && status < 300) {
                    return responseText;
                } else {
                    throw new RuntimeException("HTTP错误 " + status + ": " + responseText);
                }
            }




//            if (status == HttpURLConnection.HTTP_OK){
//                try(BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"))){
//                    StringBuilder response = new StringBuilder();
//                    String responseLine;
//                    while ((responseLine=br.readLine())!=null){
//                        response.append(responseLine.trim());
//                    }
//                    return response.toString();
//                }
//            }else {
//
//                try(BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(),"utf-8"))){
//                    StringBuilder response = new StringBuilder();
//                    String responseLine;
//                    while ((responseLine=br.readLine())!=null){
//                        response.append(responseLine.trim());
//                    }
//                    throw new RuntimeException("HTTP错误：" + status + ",响应：" + response.toString());
//                }
//            }
        }catch (Exception e){
            // 提供更详细的错误信息
            String errorMsg = "HTTP请求失败: " + e.getMessage();
            if (e instanceof java.net.UnknownHostException) {
                errorMsg = "无法解析主机名，请检查网络连接和URL: " + urlStr;
            } else if (e instanceof java.net.ConnectException) {
                errorMsg = "连接被拒绝，请检查目标服务是否运行: " + urlStr;
            } else if (e instanceof java.net.SocketTimeoutException) {
                errorMsg = "连接超时，请检查网络连接或增加超时时间: " + urlStr;
            }
            throw new RuntimeException(errorMsg, e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
